#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
#include <stdlib.h>
 
#define MAXLINE 1024*10

int post(char *ip,int port,char *page,char *msg){
    int sockfd,n;
    char recvline[MAXLINE];
    struct sockaddr_in servaddr;
    char content[4096];
    char content_page[100];
    //定义
    sprintf(content_page,"POST /%s HTTP/1.1\r\n",page);
    char content_host[50];
    sprintf(content_host,"HOST: %s:%d\r\n",ip,port);
    //配置applitcation/json
    char content_type[] = "Content-Type: application/json\r\n";
    char content_len[50];
    sprintf(content_len,"Content-Length: %d\r\n\r\n",(int)strlen(msg));
    sprintf(content,"%s%s%s%s%s",content_page,content_host,content_type,content_len,msg);
    if((sockfd = socket(AF_INET,SOCK_STREAM,0)) < 0)
        printf("socket error\n");
    bzero(&servaddr,sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(9999);
    if(inet_pton(AF_INET,ip,&servaddr.sin_addr) <= 0)
        printf("inet_pton error\n");
    //建立连接
    if(connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr)) < 0)
        printf("connect error\n");
    printf("sockfd=%d\ncontent=%s\n",sockfd,content);
    //发送Http请求
    if(-1 == write(sockfd,content,sizeof(content))) 					
    {  
        printf("send http package fail!\r\n");  
        return -1;  
    }
    //接受http post 回复的json信息
    while((n = read(sockfd,recvline,MAXLINE)) > 0)
    {
        recvline[n] = 0;
        if(fputs(recvline,stdout) == EOF)
            printf("fputs error\n");
    }
}
 
int main()
{
    char msg[] =  "{\
                      \"atAll\": false,\
                      \"content\": \"test_Avensliu\",\
                      \"messageType\": \"text\"\
                   }";
    char ip[] = "172.16.182.230";
    int port = 9999;
    char page[] = "dingtalk/rest/plugin/service/dingtalk/text";
    post(ip,port,page,msg);
    exit(0);
}